package com.cdhk.service.impl;

import cn.hutool.core.io.FileUtil;
import com.cdhk.constant.ErrorCodeEnum;
import com.cdhk.dto.ExportFileDTO;
import com.cdhk.service.CommonService;
import com.ty.basic.utils.PathUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
@Slf4j
public class CommonServiceImpl implements CommonService {
    @Value("${file.default.dir}")
    private String fileExportDefaultDir;

    @Override
    public String getFilePath(String modelPath) {
        if (org.apache.commons.lang3.StringUtils.isBlank(modelPath)) {
            throw ErrorCodeEnum.NOT_FOUND_FILE_TEMPLATE.getException("模板路径为空，请检查配置！");
        }
        String jarPath = PathUtil.getProjectPath();
        String path = jarPath + File.separator + modelPath;
        log.info("===========提示信息================> 模板文件路径为：{}", path);
        File file = new File(path);
        if (!file.exists()) {
            log.info("===========提示信息===================> 模板文件不存在");
            ClassPathResource resource = new ClassPathResource(File.separator + modelPath);
            if (!resource.exists()) {
                throw ErrorCodeEnum.NOT_FOUND_FILE_TEMPLATE.getException("模板文件不存在，请检查配置");
            }
            try {
                return resource.getURI().getPath();
            } catch (IOException ioException) {
                throw ErrorCodeEnum.NOT_FOUND_FILE_TEMPLATE.getException("获取模板文件异常，请检查配置");
            }
        }
        String absolutePath = file.getAbsolutePath();
        log.info("============提示信息==============> 模板路径为：{}", absolutePath);
        return absolutePath;
    }

    @Override
    public ExportFileDTO getDestFile(String destFileName) {
        if (org.apache.commons.lang3.StringUtils.isBlank(fileExportDefaultDir)) {
            throw ErrorCodeEnum.NOT_FOUND_FILE_TEMPLATE.getException("临时目录未配置，请检查");
        }
        File file = new File(fileExportDefaultDir);
        if (!file.exists()) {
            FileUtil.mkdir(file);
        }
        if (!destFileName.contains(".")) {
            String fileName = destFileName + ".xlsx";
            String filePath = file.getAbsolutePath() + File.separator + fileName;
            log.info("===========提示信息============> 目标文件路径为：{}", filePath);
            return new ExportFileDTO().setFileName(fileName).setFilePath(filePath);
        }
        String filePath = file.getAbsolutePath() + File.separator + destFileName;
        log.info("===========提示信息============> 目标文件路径为：{}", filePath);
        return new ExportFileDTO().setFileName(destFileName).setFilePath(filePath);
    }
}
